<!--*************************************
* @update:  2022-12-08  zhangzhenmeng  [创建文件]
* 
* @description: 上传图片
****************************************-->

<template>
  <div class="a-upload-img">
    <div class="btn-box" @click="isShowModal = true">
      <div v-if="!imgSrc">点击上传</div>
      <img
        v-else-if="isImgType(imgSrc)"
        class="soucre-item"
        :src="imgSrc"
        title="点击更换资源"
        alt=""
      />
      <video
        v-else
        class="soucre-item"
        :src="imgSrc"
        controlsList="nodownload"
        disablePictureInPicture
        title="点击更换资源"
      ></video>
    </div>
    <!-- :bodyStyle="{ height: '372px' }" -->
    <a-modal
      centered
      :maskClosable="false"
      v-model:visible="isShowModal"
      title="上传资源"
      @ok="submit"
      @cancel="reset"
    >
      <template #footer>
        <div style="display: flex; justify-content: space-between">
          <a-button key="back" @click="resetNo">取消选中</a-button>
          <div>
            <a-button key="back" @click="reset">取消</a-button>
            <a-button key="submit" type="primary" @click="submit"
              >确定</a-button
            >
          </div>
        </div>
      </template>
      <a-form>
        <a-form-item label="上传入口">
          <a-radio-group v-model:value="type" @change="typeChange">
            <a-radio value="本地上传">本地上传</a-radio>
            <a-radio value="资源库">资源库</a-radio>
            <a-radio value="项目缓存">项目缓存</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item v-if="type == '本地上传'" label="上传文件">
          <a-upload-dragger
            :accept="acceptData()"
            :customRequest="customRequest"
            name="file"
            :multiple="false"
            :showUploadList="false"
            @change="uploadChange"
            @reject="acceptReject"
          >
            <div class="upload-box">
              <video
                class="show-img"
                v-if="showUrlType === 'video'"
                :src="showUrl"
              ></video>
              <img
                class="show-img"
                v-else-if="showUrlType === 'image'"
                :src="showUrl"
                alt=""
              />
              <div v-else class="content">
                <FolderOpenOutlined class="content-icon" />
                <span class="content-text">点击或拖放文件至此处进行上传</span>
              </div>
            </div>
          </a-upload-dragger>
          <a-checkbox
            :style="{ marginTop: '10px' }"
            v-model:checked="localForm.syncres"
            >保存到资源库</a-checkbox
          >
        </a-form-item>
        <a-form-item v-if="type == '资源库'" label="资源库类型">
          <a-radio-group
            v-model:value="form.soucre"
            @change="
              () => {
                getAllSoucre();
              }
            "
          >
            <a-radio value="system">系统资源</a-radio>
            <a-radio value="user">我的资源</a-radio>
          </a-radio-group>
        </a-form-item>
        <div v-if="type != '本地上传'" class="source-box">
          <div
            class="soucre-content"
            v-for="(item, index) in fileData"
            v-show="isShowItem(item.name || item.fileName)"
            :key="index"
          >
            <div
              v-if="item.isdir == 1"
              @dblclick="openFile(item)"
              class="soucre-team"
            ></div>
            <div
              :class="
                index === checkIndex
                  ? 'soucre-item-box active'
                  : 'soucre-item-box'
              "
              @click="checkIndex = index"
            >
              <img
                v-if="isImgType(item.name || item.fileName)"
                class="soucre-item"
                :src="getFileUrl(item)"
                alt=""
              />
              <video
                v-else
                class="soucre-item"
                :src="getFileUrl(item)"
                controlsList="nodownload"
                disablePictureInPicture
              ></video>
            </div>
            <div class="soucre-label">{{ item.name }}</div>
          </div>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import { LoadingOutlined } from "@ant-design/icons-vue";

export default {
  des: "上传图片",
  name: "aUploadImg",
  components: {
    LoadingOutlined,
  },
  props: {
    imgSrc: {
      type: String,
      default: "",
    },
    projectId: {
      type: String,
      default: (window.location.hash.match(/projectId=([a-zA-Z0-9]+)/) ||
        [])[1],
    },
    category: {
      type: String,
      default: ""
    },
  },
  emits: ["update:imgSrc"],
  setup() {},
  data() {
    return {
      imagePicker: "",
      type: "本地上传",
      showUrl: "", // 预览资源url
      showUrlType: "", // 预览资源类型
      isShowModal: false,
      fileData: [],
      projectFileData: [],
      acceptImgArr: [".jpg", ".jpeg", ".png", ".svg", ".gif", ".webp", ".ico", ".bmp"],
      acceptVideoArr: [".ogg", ".mp4", ".webm", ".mov"],
      localForm: {
        file: "",
        syncres: false,
      },
      form: {
        type: "本地上传",
        soucre: "system",
      },
      teamSelectArr: [
        {
          value: "system",
          label: "系统资源",
          children: [],
        },
        {
          value: "user",
          label: "我的资源",
          children: [],
        },
      ],
      checkIndex: "",
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    // this.init()
  },
  activated() {},
  methods: {
    init() {
      this.initData();
    },
    backgroundImageChange() {},
    initData() {},
    acceptData() {
      let arr = [];
      if (this.category === "img") {
        arr = [...this.acceptImgArr].join(',');
      }
      if (this.category === "video") {
        arr = [...this.acceptVideoArr].join(',');
      }
      if (!this.category) {
        arr = [...this.acceptImgArr, ...this.acceptVideoArr].join(',');
      }
      return arr;
    },
    isShowItem(str) {
      let temp = str.split('.');
      let fileType = temp[1] ? `.${temp[1]}` : '';
      if (this.acceptImgArr.includes(fileType)) {
        if (this.category === "img") {
          return true;
        } else {
          return false;
        }
      } else if (this.acceptVideoArr.includes(fileType)) {
        if (this.category === "video") {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    },
    handleDrop(e) {},
    openFile(item) {
      this.getAllSoucre(item.path);
    },
    getFileUrl(item) {
      if (this.type == "资源库") {
        return `/mock/api/resource/RES_GET?rtype=${this.form.soucre}&fpath=${item.path}`;
      }
      return item.fpath;
    },
    isImgType(str) {
      var result = false;
      this.acceptImgArr.forEach((item) => {
        if (str.indexOf(item) != -1) result = true;
      });
      return result;
    },
    typeChange() {
      if (this.type == "资源库") this.getAllSoucre();
      if (this.type == "项目缓存") this.getProjectCache();
    },
    // 获取资源
    async getAllSoucre(fpath) {
      this.checkIndex = "";
      this.fileData = [];
      const params = {
        rtype: this.form.soucre,
        fpath: fpath,
        full: 0,
      };
      const res =
        (await axios.get("/mock/api/resource/RES_ENUM", { params })) || {};
      this.fileData = res.data;
      // return compTypes;
    },
    // 获取项目缓存
    async getProjectCache() {
      this.checkIndex = "";
      this.fileData = [];
      const params = {
        fpath: "upload/" + this.projectId,
      };
      const res =
        (await axios.get("/mock/api/project/ENUM_PRJ_FILE", { params })) || {};
      this.fileData = res.data;
      // return compTypes;
    },
    customRequest() {
      return false;
    },
    uploadChange(info) {
      const type = info.file.type.split("/")[0];
      if (type == "image") {
        const photoMaxSize = info.file.size / 1024 / 1024 < 10;
        if (!photoMaxSize) {
          this.$message.error("图片不能大于10MB!");
          return false;
        }
        this.showUrlType = "image";
      } else if (type == "video") {
        const videoMaxSize = info.file.size / 1024 / 1024 < 20;
        if (!videoMaxSize) {
          this.$message.error("视频不能大于20MB!");
          return false;
        }
        this.showUrlType = "video";
      }
      this.localForm.file = info.file;
      this.getBase64(info.file.originFileObj, (base64Url) => {
        this.showUrl = base64Url;
      });

      this.getBase64(info.file.originFileObj, (base64Url) => {
        this.showUrl = base64Url;
      });
    },
    getBase64(img, callback) {
      const reader = new FileReader();
      reader.addEventListener("load", () => callback(reader.result));
      reader.readAsDataURL(img);
    },
    acceptReject(data) {
      this.$message.error(
        `图片支持格式：jpg、jpeg、png、svg、gif、webp、ico 视频支持格式：ogg、mp4、webm、mov`
      );
    },
    async submitUpload() {
      if (!this.localForm.file) {
        this.$message.error("请上传文件!");
        return;
      }
      const formData = new FormData();
      formData.append(
        "fpath",
        `upload/${this.projectId || 'VTools'}/${this.localForm.file.name}`
      );
      formData.append("file", this.localForm.file.originFileObj);
      formData.append("syncres", this.localForm.syncres ? 1 : 0);
      const res = await axios.post("/mock/api/project/UP_PRJ_FILE", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      //成功
      if (res && res.err === 0) {
        this.$message.success("上传成功！");
        this.$emit("update:imgSrc", res.data.fpath);
      } else {
        this.$message.error("上传失败！");
      }
      this.reset();
    },
    async submitSoucre() {
      if (this.checkIndex === "") {
        this.$message.error("请选择文件!");
        return;
      }
      const params = {
        rtype: this.form.soucre,
        src: this.fileData[this.checkIndex].path,
        dst:
          "upload/" +
          this.projectId +
          "/" +
          this.fileData[this.checkIndex].name,
      };
      const res =
        (await axios.get("/mock/api/resource/COPY_TO_RES", { params })) || {};
      if (res && res.err === 0) {
        this.$message.success("成功将资源复制到项目缓存！");
        this.$emit("update:imgSrc", res.data.fpath);
      } else {
        this.$message.error("复制失败！");
      }
      this.reset();
    },
    submit() {
      if (this.type === "本地上传") this.submitUpload();
      if (this.type === "资源库") this.submitSoucre();
      if (this.type === "项目缓存") {
        if (this.checkIndex === "") {
          this.$message.error("请选择文件!");
          return;
        }
        this.$emit("update:imgSrc", this.fileData[this.checkIndex].fpath);
        this.reset();
      }
    },
    reset() {
      this.checkIndex = "";
      this.type = "本地上传";
      this.showUrl = "";
      this.showUrlType = "";
      this.localForm = {
        file: "",
        syncres: false,
      };
      this.isShowModal = false;
    },
    resetNo() {
      this.reset();
      this.$emit("update:imgSrc", "");
    },
  },
  deactivated() {},
  beforeUnmount() {},
};
</script>

<style lang="less" scoped>
:deep(.upload-box) {
  height: 136px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: @Gray_4;
  border: 1px solid @Gray_3;
  border-radius: 2px;
  .show-img {
    max-width: 100%;
    max-height: 100%;
  }
  .content {
    width: 216px;
    height: 80px;
    border: 1px dashed @Gray_3;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: @Text_2;

    .content-icon {
      font-size: 20px;
    }
    .content-text {
      font-size: 13px;
      margin-top: 8px;
    }
  }
}
:deep(.ant-upload) {
  display: block;
  width: 100%;
  height: 100%;
  background-color: @Gray_4 !important;
  border: unset;
  .ant-upload-btn {
    padding: 0;
    .ant-upload-drag-container {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
    }
  }
}
.a-upload-img {
  .btn-box {
    display: flex;
    // width: calc(100% - 1.5em);
    width: 100%;
    height: 80px;
    // margin-left: 1.5em;
    margin-bottom: 14px;
    background-color: @Gray_4;
    text-align: center;
    line-height: 80px;
    cursor: pointer;
    .soucre-item {
      max-width: 100%;
      max-height: 100%;
      border: 1px dashed rgba(255,255,255,0.2);
    }
  }
}
:deep(.source-box) {
  width: 480px;
  height: 232px;
  padding-top: 10px;
  padding-left: 20px;
  background: @Gray_4;
  border: 1px solid @Gray_3;
  overflow-y: auto;
  .soucre-content {
    display: inline-block;
    width: 74px;
    height: 97px;
    position: relative;
    // margin-bottom: 20px;
    margin-right: 15px;
    .soucre-team {
      width: 74px;
      height: 74px;
      border-radius: 5px;
      cursor: pointer;
      background: url("~assets/images/system_soucre/bg.png") no-repeat
        center/100% 100%;
    }
    .soucre-item-box {
      position: relative;
      width: 74px;
      height: 74px;
      border: 2px solid @Gray_4;
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      &:hover {
        border: 2px solid @Brand_1;
      }
      cursor: pointer;
      .soucre-item {
        max-width: 69px;
        max-height: 69px;
        height: 69px;
        border-radius: 5px;
      }
    }
    .active {
      border: 2px solid @Brand_1;
    }
    .soucre-label {
      text-align: center;
      position: absolute;
      bottom: 0;
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      font-size: 12px;
    }
  }
}
</style>